//
//  BCDateBase.m
//  Memo
//
//  Created by bonc on 13-9-3.
//  Copyright (c) 2013年 fuzhengbang. All rights reserved.
//

#import "BCDateBase.h"
#import "NSDate+Calendar.h"

@implementation BCDateBase
@synthesize mybase;

+(BCDateBase*)defaultBase
{
    static FMDatabase* dataBase;
    if (!dataBase) {
        NSArray* pathArray=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString* dirctoryPath=[pathArray lastObject];
        NSString* destinationFilePath=[dirctoryPath stringByAppendingPathComponent:@"MemoDataBase.sqlite"];
        NSLog(@"destinationFilePath=%@",destinationFilePath);
        NSFileManager* fManager=[NSFileManager defaultManager];
        if (![fManager fileExistsAtPath:destinationFilePath]) {
            NSString* sourceFilePaht=[[NSBundle mainBundle] pathForResource:@"MemoDataBase" ofType:@"sqlite"];
            NSError* error;
            [fManager copyItemAtPath:sourceFilePaht toPath:destinationFilePath error:&error];
            if (error) {
                NSLog(@"Copy dataBase to documentDirectory failed");
            }
        }
        dataBase=[[FMDatabase alloc]initWithPath:destinationFilePath];
    }
    BCDateBase *base=[[BCDateBase alloc]init];
    base.mybase=dataBase;
    return base;
}

-(BOOL)openDB
{
    if (![mybase open]) {
        return NO;
    }
    return YES;
}

-(BOOL)closeDB
{
    if (![mybase close]) {
        return NO;
    }
    return YES;
}

//查询某天的所有记录
-(NSArray*)allNotesOnDate:(NSDate*)aDate
{
    NSDateComponents* comp=[[NSDateComponents alloc]init];
    [comp setHour:-8];
    NSDate* date=[[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:aDate options:0];
    NSInteger year,month,day,hour;
    year=[date  year];
    month=[date month];
    day=[date day];
    hour=[date hour];
    [self openDB];
    FMResultSet* resultSet=[mybase executeQuery:@"SELECT * FROM MemoNotes WHERE Year=? AND Month=? AND Day=?",[NSNumber numberWithInt:year],[NSNumber numberWithInt:month],[NSNumber numberWithInt:day]];
    if (!resultSet) {
        NSLog(@"Query for all notes failed");
    }
    NSMutableArray* notes=[[NSMutableArray alloc]init];
    while ([resultSet next]) {
        NSInteger year=[resultSet intForColumn:@"Year"];
        NSInteger month=[resultSet intForColumn:@"Month"];
        NSInteger day=[resultSet intForColumn:@"Day"];
        NSInteger hour=[resultSet intForColumn:@"Hour"];
        NSInteger minute=[resultSet intForColumn:@"Minute"];
        NSDate* date=[NSDate dateWithYear:year Month:month Day:day Hour:hour Minute:minute];
        NSString* note=[resultSet stringForColumn:@"Note"];
        NSNumber* alertMode=[resultSet objectForColumnName:@"AlertMode"];
        [notes addObject:@{kDateKey: date,kContentKey: note,kAlertMode:alertMode}];
    }
    
    [self closeDB];
    
    NSArray* memos=[notes sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSDate* date1=[obj1 valueForKey:kDateKey];
        NSDate* date2=[obj2 valueForKey:kDateKey];
        return [date1 compare:date2];
            }];
    return memos;
}

//查询某天的记录总数
-(NSInteger)theNumberOfNotesOnDay:(NSDate*)aDate
{
    return [[self allNotesOnDate:aDate] count];
}

//插入一条新的记录
-(BOOL)insertANewNoteOnTime:(NSDate*)deadline withCotent:(NSString*)content AlertMode:(BCAlertMode) alertMode;
{
    NSDateComponents* comp=[[NSDateComponents alloc]init];
    [comp setHour:-8];
    NSDate* date=[[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:deadline options:0];
    NSInteger year,month,day,hour,minute;
    year=[date year];
    month=[date month];
    hour=[date hour];
    day=[date day];
    minute=[date minute];
    NSLog(@"deadline=%@,y=%d,M=%d,d=%d,h=%d,m=%d",deadline,year,month,day,hour,minute);
    [self openDB];
    BOOL result=[mybase executeUpdate:@"INSERT INTO MemoNotes(Year,Month,Day,Hour,Minute,Note,AlertMode) VALUES(?,?,?,?,?,?,?)",[NSNumber numberWithInteger:year],[NSNumber numberWithInteger:month],[NSNumber numberWithInteger:day],[NSNumber numberWithInteger:hour],[NSNumber numberWithInteger:minute],content,[NSNumber numberWithInteger:alertMode]];
    [self closeDB];
    return result;
}

//修改一条记录
-(BOOL)UpdateANoteOnTime:(NSDate*)aDate withContent:(NSString*)content AlertMode:(BCAlertMode)alertMode  toNewContent:(NSString*)newContent andAlertMode:(BCAlertMode)newAlertMode
{
    NSDateComponents* comp=[[NSDateComponents alloc]init];
    [comp setHour:-8];
    NSDate* date=[[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:aDate options:0];
    NSInteger year,month,day,hour,minute;
    year=[date year];
    month=[date month];
    hour=[date hour];
    day=[date day];
    minute=[date minute];
    [self openDB];
    BOOL result=NO;
    if (newContent&&(![newContent isEqualToString:content]||alertMode!=newAlertMode)) {
        result=[mybase executeUpdate:@"UPDATE MemoNotes SET Note=?,AlertMode=? WHERE Year=? AND Month=? AND Day=? AND Hour=? AND Minute=? AND Note=? AND AlertMode=?",newContent,[NSNumber numberWithInteger:newAlertMode],[NSNumber numberWithInteger:year],[NSNumber numberWithInteger:month],[NSNumber numberWithInteger:day],[NSNumber numberWithInteger:hour],[NSNumber numberWithInteger:minute],content,[NSNumber numberWithInteger:alertMode]];
    }
    [self closeDB];
    return result;
}

//删除一条记录
-(BOOL)deleteANoteOnTime:(NSDate*)aDate withContent:(NSString*)content AlertMode:(BCAlertMode)alertMode
{
    NSDateComponents* comp=[[NSDateComponents alloc]init];
    [comp setHour:-8];
    NSDate* date=[[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:aDate options:0];
    NSInteger year,month,day,hour,minute;
    year=[date year];
    month=[date month];
    hour=[date hour];
    day=[date day];
    minute=[date minute];
    
    [self openDB];
    BOOL result=NO;
    if (aDate!=nil&&content!=nil) {
        [self openDB];
        result=[mybase executeUpdate:@"DELETE FROM MemoNotes WHERE Note=? AND Year=? AND Month=? AND Day=? AND Hour=? AND Minute=? AND AlertMode=?",content,[NSNumber numberWithInteger:year],[NSNumber numberWithInteger:month],[NSNumber numberWithInteger:day],[NSNumber numberWithInteger:hour],[NSNumber numberWithInteger:minute],[NSNumber numberWithInteger:alertMode]];
        [self closeDB];
        return result;
    }else if (aDate!=nil){
        [self openDB];
        result=[mybase executeUpdate:@"DELETE FROM MemoNotes WHERE Year=? AND Month=? AND Day=? AND Hour=? AND Minute=?",year,month,day,hour,minute];
        [self closeDB];
        return result;
    }else if (content!=nil){
        [self openDB];
        result=[mybase executeUpdate:@"DELETE FROM MemoNotes WHERE Note=?",content];
        [self closeDB];
        return result;
    }
    NSLog(@"Wrong parameters send ,when deleting a note!");
    return result;
}

//删除所有过期的任务
-(BOOL)deleteNotesBeforeTime:(NSDate*)aDate
{
    NSDateComponents* comp=[[NSDateComponents alloc]init];
    [comp setHour:-8];
    NSDate* date=[[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:aDate options:0];
    NSInteger year,month,day,hour,minute;
    year=[date year];
    month=[date month];
    hour=[date hour];
    day=[date day];
    minute=[date minute];
    [self openDB];
    BOOL yearOperation=[mybase executeUpdate:@"DELETE FROM MemoNotes WHERE Year<?",[NSNumber numberWithInteger:year]];
    BOOL monthOperation=[mybase executeUpdate:@"DELETE FROM MemoNotes WHERE Year=? AND Month<?",[NSNumber numberWithInteger:year],[NSNumber numberWithInteger:month]];
    BOOL dayOperation=[mybase executeUpdate:@"DELETE FROM MemoNotes WHERE Month=? AND Day<?",[NSNumber numberWithInteger:month],[NSNumber numberWithInteger:day]];
    [self closeDB];
    if (yearOperation&&monthOperation&&dayOperation) {
        return YES;
    }
    NSLog(@"delete notes before time failed");
    return NO;
}
@end
